import { useState, useEffect } from 'react';
import { debounce } from 'lodash';
/**
 * 获取字符串字符长度
 * @param str
 * @returns
 */
export const getStrLength = (str:string) => {
  let number = 0;
  for (let i = 0; i < str.length; i += 1) {
    if (str.charCodeAt(i) > 255) { number += 1; } else { number += 0.5; }
  }
  return number;
};

/**
 * 设置全屏/退出全屏
 * @param ele 元素
 * @param bl 开启/关闭
 * @returns
 */
// export const handleFullScreen = (ele:any, bl:boolean) => {
//   if (bl) {
//     if (ele.requestFullscreen) {
//       ele.requestFullscreen();
//     } else if (ele.webkitRequestFullScreen) {
//       ele.webkitRequestFullScreen();
//     } else if (ele.mozRequestFullScreen) {
//       ele.mozRequestFullScreen();
//     } else if (ele.msRequestFullscreen) {
//       ele.msRequestFullscreen();
//     }
//   } else if (document.exitFullscreen) {
//     document.exitFullscreen();
//   } else if (document.webkitCancelFullScreen) {
//     document.webkitCancelFullScreen();
//   } else if (document.mozCancelFullScreen) {
//     document.mozCancelFullScreen();
//   } else if (document.exitFullscreen()) {
//     document.msExitFullscreen();
//   }
// };
/**
 * 自定义hooks，监听浏览器窗口变化了
 */
export const useResize = () => {
  const [size, setSize] = useState<boolean>(true);
  const [screenWidth, setWidth] = useState<number>(0);
  const updateWindow = () => {
    const width:number = document.body.clientWidth;
    setSize(false);
    setWidth(width);
    setTimeout(() => {
      setSize(true);
    }, 0);
  };
  useEffect(() => {
    window.addEventListener('resize', debounce(updateWindow, 500), false);
    return () => {
      window.removeEventListener('resize', debounce(updateWindow, 500), false);
    };
  }, [screenWidth]);

  return size;
};

/**
 * 钱转化为打点数据，从分开始，三位一打点
 */
export const moneyDian = (s:any, n:any) => {
  let num:any = 0;
  let str:any = '';
  num = num > 0 && num <= 20 ? num : 2;
  str = `${parseFloat((`${s}`).replace(/[^\d.-]/g, '')).toFixed(num)}`;
  const l = str.split('.')[0].split('').reverse();
  const r = str.split('.')[1];
  let t = '';
  for (let i = 0; i < l.length; i += 1) {
    t += l[i] + ((i + 1) % 3 === 0 && (i + 1) !== l.length ? ',' : '');
  }
  return `${t.split('').reverse().join('')}.${r}`;
};
